<template>
  <div id="div1">

  </div>
</template>

<script>
import wangeditor from 'wangeditor'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import qs from 'qs'

export default {
  name: "WangEditor",
  props: ['catchData', 'content'],    // 接收父组件的方法
  components: {
    wangeditor,
  },
  mounted() {
    this.editor = new wangeditor('#div1');
    this.editor.config.height = 450;
    this.editor.highlight = hljs;
    this.editor.config.onchange = (html) => {
      this.$emit('getArticle', html);
    }
    //跨域传递cookie
    this.editor.config.withCredentials = true;
    //自定义文件上传参数名
    this.editor.config.uploadFileName = 'imgFile';
    //设置文件上传路径
    this.editor.config.uploadImgServer = '/Test_war_exploded/blog/uploadImg';
    //自定义图片上传事件
    this.editor.config.uploadImgHooks = {
      before: function (xhr, editor, files) {

      },
      success: function (xhr, editor, result) {
        console.log("上传成功");
      },
      fail: function (xhr, editor, result) {
        console.log("上传失败,原因是" + result);
      },
      error: function (xhr, editor) {
        console.log("上传出错");
      },
      timeout: function (xhr, editor) {
        console.log("上传超时");
      }
    };
    //自定义图片上传
    let that=this;
    this.editor.config.customUploadImg = function (files, insertImg) {
      let formData = new FormData();
      for(let i = 0;i < files.length;i ++) {
        formData.append("imgFile", files[i], files[i].name);

      }
      that.axios.post('/blog/uploadImg', formData, {     // 上传图片接口
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then((response) => {
        if(response.data.errno === 0){
          for(let j=0;j<response.data.data.length;j++){
            insertImg(response.data.data[j]);    //  前面这个ip地址是服务器ip，后面的imgUrl是后台返回的图片地址，拼接上就是图片路径
          }
        }else{

        }
      })
    };
    this.editor.create();
    this.editor.txt.html(this.content);
  },
  data() {
    return {
      editor: '',
    }
  },
  watch: {
    content: function () {
      this.clearEditor();
    }
  },
  methods: {
    clearEditor() {
      if (this.content === '') {
        this.editor.txt.clear();
      }
    }
  },
}
</script>

<style scoped>

</style>
